package com.app.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.app.observers.HostListObserver;
import com.app.observers.HostListSubject;
import com.app.task.Task;

public class BroadcastListener extends Task implements HostListSubject {

	private DatagramSocket socket;
	private DatagramPacket packet;
	//private ConcurrentHashMap<InetAddress, String> hosts = new ConcurrentHashMap<InetAddress, String>();
        private InetAddress host;
	private ArrayList<HostListObserver> observers = new ArrayList<HostListObserver>();
	
	public BroadcastListener(int port) {
		try {
			socket = new DatagramSocket(port);
			socket.setBroadcast(true);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		
		packet = new DatagramPacket(new byte[40], 40);
	}
	@Override
	protected void task() {
		try {
			socket.receive(packet);
			String data = new String(packet.getData());
			host = packet.getAddress();
			notifyHostObservers();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	@Override
	public void registerObserver(HostListObserver observer) {
		observers.add(observer);
		
	}
	@Override
	public void removeObserver(HostListObserver observer) {
		observers.remove(observer);
	}
	@Override
	public void notifyHostObservers() {
		for(HostListObserver ob : observers){
			ob.updateHost(host);
		}
	}

}
